package com.hw.one.dam2.dao;

import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.param.SmallAirParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/06/13 14:28.
 */
@Repository(value = "sourceDataDao")
public class SourceDataDao implements ISourceDataDao {

    @Autowired
    private MongoTemplate mongoTemplateStandardSiteData;


    @Override
    public List<Map> findSourceDataListBySnCode(String snCode) {
        SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.NO_SPLIT_SDF_YM);
        String tableName = sdf.format(new Date());
        // 查询条件
        Criteria criteria = Criteria.where("SNCODE").is(snCode);
        Query query = new Query(criteria).with(new Sort(Sort.Direction.DESC, "MONITORTIME")).limit(60);

        return mongoTemplateStandardSiteData.find(query, Map.class, "T_DATA_SC_COLLECT-" + tableName);
    }

    @Override
    public Map findScCollectMin5NewMinuteOneDataBySnCode(String snCode) {
        // 获取最新记录
        Map newData = mongoTemplateStandardSiteData.findOne(
                new Query(Criteria.where("SNCODE").is(snCode)).with(new Sort(Sort.Direction.DESC, "MONITORTIME")), Map.class,
                "T_DATA_SC_COLLECT_MIN5");
        return newData;
    }

    @Override
    public void insertScreenDataData(Map<String, Object> map) {
        mongoTemplateStandardSiteData.insert(map, "T_DATA_SC_SCREEN_DATA_MIN");
    }

    @Override
    public List<Map> findScreenDataDataBySNCodeListAndTime(SmallAirParam smallAirParam) {
        // 查询条件
        Criteria criteria = Criteria.where("SNCODE").in(smallAirParam.getSiteCodes());
        criteria.and("MONITORTIME").gte(smallAirParam.getStartTime()).lte(smallAirParam.getEndTime());
        Query query = new Query(criteria).with(new Sort(Sort.Direction.DESC, "MONITORTIME"));

        return mongoTemplateStandardSiteData.find(query, Map.class, "T_DATA_SC_SCREEN_DATA_MIN");
    }

    @Override
    public Map findScreenDataNewMinBySNCode(String snCode) {
        // 获取最新记录
        Map newData = mongoTemplateStandardSiteData.findOne(
                new Query(Criteria.where("SNCODE").is(snCode)).with(new Sort(Sort.Direction.DESC, "MONITORTIME")), Map.class,
                "T_DATA_SC_SCREEN_DATA_MIN");
        return newData;
    }
}
